package marcheba.itaka.view;

import marcheba.itaka.DataStore;
import marcheba.itaka.R;
import marcheba.itaka.entities.Itaka;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.apphance.android.Log;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAuthorizationRequestUrl;

public class LoginPageActivity extends Activity {

	protected static final String TAG = "LoginPageActivity";

	private WebView webView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		Log.i(TAG, "onCreate");
		setContentView(R.layout.loginpage);
		webView = (WebView) findViewById(R.id.webView1);
		webView.getSettings().setJavaScriptEnabled(true);

		CookieSyncManager.createInstance(this);
		setResult(RESULT_CANCELED);
		webView.setWebViewClient(new WebViewClient() {

			@Override
			public void onPageFinished(WebView view, String url) {

				Intent result = new Intent();
				String title = view.getTitle();
				if (title == null)
					return;

				String[] parts = title.split("=");
				if (parts.length == 2
						&& parts[0].equalsIgnoreCase("Success code")) {
					Log.i(TAG, "onPageFinished(): Successed authentication " );
					result.putExtra(Itaka.AUTH_CODE, parts[1]);
					setResult(RESULT_OK, result);
					finish();
				}
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {

				super.onPageStarted(view, url, favicon);
			}
		});

		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onStart() {
		Log.i(TAG, "onStart()");
		String authorizeUrl = new GoogleAuthorizationRequestUrl(getResources()
				.getString(R.string.ClientID), getResources().getString(
				R.string.CallbackUrl), getResources().getString(
				R.string.UserInfoScope)).build();
		CookieSyncManager.getInstance().startSync();
		android.webkit.CookieManager.getInstance().removeAllCookie();
		CookieSyncManager.getInstance().stopSync();

		webView.loadUrl(authorizeUrl);
		Log.i(TAG, "onStart()" + "Begin of authentication");

		super.onStart();
	}

	@Override
	protected void onStop() {

		super.onStop();
	}

}
